from django.contrib.auth import logout
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from times import now

from blog.models import User
#功能包括用户登录、注册、登出

#用户灯录判断
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        Account = request.POST.get('UserAccount')
        Password = request.POST.get('UserPassword')
        if len(Account) != 8:
            return HttpResponse('account_error')
        else:
            user = User.objects.get(UserAccount=Account)
            if user is None:
                return HttpResponse('account_none')
            else:
                if user.UserPassword == Password:
                    request.session['is_login'] = True
                    request.session['UserName'] = user.UserName
                    request.session['id'] = user.id
                    user.Last_login = now()
                    user.save()
                    return redirect('index')
                else:
                    return HttpResponse('password_error')

#新用户据注册
class CreateView(View):
    def get(self, request):
        return render(request, 'create.html')

    def post(self, request):
        Name = request.POST.get('UserName')
        Account = request.POST.get('UserAccount')
        user_exists = User.objects.filter(UserAccount=Account).exists()

        if user_exists:
            return HttpResponse('账号已存在')
        else:
            Password = request.POST.get('UserPassword')
            Password_a = request.POST.get('UserPassword_a')

            if Password_a != Password:
                return HttpResponse('密码不匹配')
            else:
                user = User()
                user.UserName = Name
                user.UserPassword = Password_a
                user.UserAccount = Account
                user.save()
                return render(request, 'login.html')

#账号登出
def logout_view(request):
    logout(request)
    return redirect('login')
def head(request):
    return render(request, 'head.html')